package BitwiseOperation.Medium;

import java.util.LinkedList;

public class LC1318 {
    public static int minFlips(int a, int b, int c) {
        LinkedList<Integer> aBinary = decimal2BinaryQueueNonNegative(a, 32),
                bBinary = decimal2BinaryQueueNonNegative(b, 32),
                cBinary = decimal2BinaryQueueNonNegative(c, 32);
        int nOperations = 0;
        for (int i = 0; i < 32; i++) {
            int aDigit = aBinary.get(i), bDigit = bBinary.get(i), cDigit = cBinary.get(i);
            if (cDigit == 0) {
                if (aDigit == 1) nOperations++;
                if (bDigit == 1) nOperations++;
            } else {
                if (aDigit == 0 && bDigit == 0) nOperations++;
            }
        }

        return nOperations;
    }

    /**
     * 将十进制非负整数转为二进制位的队列。队列中的元素只为0或1。将队列中的元素依次出队，先出队的元素位于低位，可以得到该十进制数的二进制表示。
     */
    private static LinkedList<Integer> decimal2BinaryQueueNonNegative(int decimal, int minNumDigits) {
        int remainder = decimal;
        LinkedList<Integer> queue = new LinkedList<>();
        while (remainder > 0) {
            queue.offer(remainder % 2);
            remainder /= 2;
        }
        int repeat = minNumDigits - queue.size();
        // 前端补0
        for (int i = 1; i <= repeat; i++) {
            queue.addLast(0);
        }

        return queue;
    }

    public static void main(String[] args) {
        int a = 2, b = 6, c = 5;
        System.out.println(minFlips(a, b, c));
    }
}
